package org.duang.sms.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.duang.config.Config;
import org.duang.sms.utils.SmsToolsKit;



final public class SmsKit {
	
	private static ISmsClientFactory<?> factory = null;
	private static List<String> phoneList;
	private static Map<String, String> paramsMap;
	private String type;
	private static SmsKit smsKit;

	public static SmsKit duang() {
		if (null == phoneList)
			phoneList = new ArrayList<String>();
		else
			phoneList.clear();
		
		if (null == paramsMap)
			paramsMap = new HashMap<String, String>();
		else
			paramsMap.clear();
		
		if(null == smsKit)
			smsKit = new SmsKit();
		
		return smsKit;
	}

	public SmsKit phone(String phones) {
		phoneList.add(phones);
		return this;
	}
	
	public SmsKit phone(List<String> phones) {
		phoneList.addAll(phones);
		return this;
	}
	
	
	public SmsKit param(String key, String value) {
		paramsMap.put(key, value);
		return this;
	}
	public SmsKit param(Map<String,String> map) {
		paramsMap.putAll(map);
		return this;
	}
	
	public SmsKit code(String code) {
		type = code;
		return this;
	}
	
	public SmsMessage send() {
		return send(phoneList, type, paramsMap);
	}
	
	
	private void  init() {
		String example = Config.getSmsClientExample();
		if(example.isEmpty()) {
			throw new NullPointerException();
		}
		factory = SmsToolsKit.newInstance(example);
		factory.getSmsClient();
	}
	
	/**
     * 批量发送短信
     * @param phoneList			接收人电话号码集合
     * @param type					自定义的短信模板代码
     * @param paramMap		要替换短信模板的参数集合
     * @return
     */
    private SmsMessage send(List<String> phoneList, String type, Map<String, String> paramMap) {
    	if(null == factory) {
			init();
		}
    	SmsMessage message = SmsToolsKit.builderSmsMessage(type);
    	message.setParams(paramMap);
    	message.setPhones(phoneList);
    	return factory.sendSms(message);
    }
    
    /**
     * 查看发送内容
     * @return
     */
    public SmsMessage show(){
    	if(null == factory) {
			init();
		}
    	SmsMessage message = SmsToolsKit.builderSmsMessage(type);
    	message.setParams(paramsMap);
    	return factory.showSms(message);
    }
    
    public boolean reloadTemplate() {
    	try{
    		SmsToolsKit.reloadTemplate();
    		return true;
    	} catch (Exception e) {
    		e.printStackTrace();
    		return false;
    	}
    }
}
